package lib.bone.audit.flow.event.sub;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import lib.bone.access.config.cycle.NepuCycle;
import lib.bone.access.config.cycle.NepuCycleService;
import lib.bone.access.constant.ResearchTypeConst;
import lib.bone.access.constant.WorkloadSourceConst;
import lib.bone.access.constant.WorkloadTypeConst;
import lib.bone.access.module.dict.DictServiceCtl;
import lib.bone.access.module.dict.entity.NepuTopicDict;
import lib.bone.audit.flow.event.EndEventService;
import lib.bone.audit.workload.attach.ResearchAttach;
import lib.bone.audit.workload.domain.NepuWorkload;
import lib.bone.audit.workload.remark.Remark;
import lib.bone.audit.workload.service.NepuWorkloadService;
import lib.bone.common.constant.ResponseCodeConst;
import lib.bone.common.exception.BusinessException;
import lib.bone.common.utils.JsonUtil;
import lib.bone.flow.domain.dto.FlowParam;
import lib.bone.flow.domain.entity.FlowWork;
import lib.bone.nepudata.domain.entity.NepuTopic;
import lib.bone.nepudata.service.ResearchServiceCtl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

@Service
public class TopicEndEvent implements EndEventService<NepuTopic, NepuTopicDict> {

    private static final String TYPE = ResearchTypeConst.TOPIC;

    @Autowired
    ResearchServiceCtl researchServiceCtl;

    @Autowired
    DictServiceCtl dictServiceCtl;

    @Autowired
    NepuWorkloadService workloadService;

    @Autowired
    NepuCycleService nepuCycleService;

    @Override
    public String getServiceType() {
        return ResearchTypeConst.TOPIC;
    }

    @Override
    public FlowParam buildFlowParam(FlowParam flowParam) {
        return null;
    }

    //构建写入工作量
    @Override
    public NepuWorkload buildWorkload(FlowParam flowParam, NepuTopic topic, NepuTopicDict nepuTopicDict) {
        NepuWorkload nepuWorkload = new NepuWorkload();
        // 获取默认工作量
//        Integer workload = topic.getWorkload();

        // 设置工作量来源 -- 申请
        nepuWorkload.setWorkloadSource(WorkloadSourceConst.APPLY);
        // 设置工作量类型 -- 科研工作量
        nepuWorkload.setWorkloadType(WorkloadTypeConst.RESEARCH);
        // 设置工作量级别
        String level = nepuTopicDict.getTopicLevel();
        nepuWorkload.setWorkloadLevel(level);
        // 设置获取工作量用户ID
        Long userId = topic.getLeaderId();
        nepuWorkload.setUserId(userId);
        //获取科研项目Id
        nepuWorkload.setLinkId(topic.getId());
        nepuWorkload.setRemark("["+topic.getCycleId()+"]"+topic.getTopicName());
        //设置工作量可分配
        nepuWorkload.setWorkloadLock(2);
        // 获取工作量所在周期 -- 从科研项目中提取
        nepuWorkload.setCycleId(topic.getCycleId());
//        String cycleId = nepuCycleService.getNowCycleId();

        // 设置父周期 = 自身
        nepuWorkload.setParentId(topic.getCycleId());

        String cycleId = nepuCycleService.getNowResearchCycleId();
        Optional<NepuCycle> nepuCycleOp = nepuCycleService.getById(cycleId);
        NepuCycle nepuCycle = new NepuCycle();
        if (Validator.isNotEmpty(nepuCycleOp)){
            BeanUtil.copyProperties(nepuCycleOp.get(),nepuCycle, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        }
        Date startDate;
        Date endDate;
        if (topic.getStartDate().compareTo(nepuCycle.getStartDate())==-1||
                topic.getStartDate().compareTo(nepuCycle.getStartDate())==0){
            startDate = nepuCycle.getStartDate();
        }else{
            startDate = topic.getStartDate();

        }
        if (topic.getEndDate().compareTo(nepuCycle.getEndDate())==-1||
                topic.getStartDate().compareTo(nepuCycle.getStartDate())==0){
            endDate = topic.getEndDate();
        }else{
            endDate = nepuCycle.getEndDate();

        }
        // 2022-5-30 bug fix 工作量计算
        long betweenMonth = DateUtil.betweenMonth(startDate,endDate,false) + 1;
        Double workload = nepuTopicDict.getWorkloadMax() * betweenMonth * 1.0 / 12;
//        BigDecimal workloads = new BigDecimal(workload);
//        nepuWorkload.setWorkload(workloads.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        nepuWorkload.setWorkload(workload);
        // 设置使用工作量为 0 用尽标识为 0
        nepuWorkload.setUsedWorkload(0.0);
        nepuWorkload.setUsedUp(0);
        // 设置工作量附加信息
        String attach = buildAttach(topic,nepuTopicDict);
        nepuWorkload.setWorkloadAttach(attach);
        // 设置锁等级为 2
        nepuWorkload.setWorkloadLock(2);
        return nepuWorkload;

    }

    @Override
    public NepuTopicDict getDict(NepuTopic topic) {
        String dictId = topic.getTopicDictId();
        Optional<Object> dictOp = dictServiceCtl.getById(dictId,TYPE);
        if (!dictOp.isPresent()){
            throw new BusinessException(ResponseCodeConst.NOT_FOUND,"ID:["+dictId+"]对应的纵向课题词典未找到");
        }
        return (NepuTopicDict) dictOp.get();
    }

    @Override
    public NepuTopic getEntity(String id) {
        Optional<Object> entityOp = researchServiceCtl.getById(id,TYPE);
        if (!entityOp.isPresent()){
            throw new BusinessException(ResponseCodeConst.NOT_FOUND,"ID:["+id+"]对应纵向课题未找到");
        }
        return (NepuTopic) entityOp.get();
    }

    @Override
    public void process(FlowWork flowWork, FlowParam flowParam) {
        String serviceId = flowParam.getServiceId();
        NepuTopic topic = getEntity(serviceId);
        NepuTopicDict dict = getDict(topic);
        NepuWorkload workload = buildWorkload(flowParam,topic,dict);
        //System.out.println("workload"+workload);
        workloadService.saveOne(workload);
    }

    @Override
    public String buildAttach(NepuTopic topic, NepuTopicDict nepuTopicDict) {
        ResearchAttach attach = new ResearchAttach();
        attach.setResearchId(topic.getId());
        attach.setResearchName(topic.getTopicName());
        attach.setDictId(nepuTopicDict.getId());
        attach.setDictName(nepuTopicDict.getTopicType());
        attach.setResearchLevel(nepuTopicDict.getTopicLevel());
        attach.setResearchType(ResearchTypeConst.TOPIC);
        return JsonUtil.obj2String(attach);
    }
//        public String buildRemark(NepuTopic nepuTopic) {
//        Remark remark = new Remark();
//        String cycleId = nepuCycleService.getNowResearchCycleId();
//        Optional<NepuCycle> nepuCycleOp = nepuCycleService.getById(cycleId);
//        NepuCycle nepuCycle = nepuCycleOp.get();
//        remark.setTopicName(nepuTopic.getTopicName());
//        remark.setCycleName(nepuCycle.getCycleName());
//        return JsonUtil.obj2String(remark);
//    }
}
